package com.epam.necklace.view.menu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.log4j.Logger;

import com.epam.necklace.logic.exceptions.NoSuchCommandException;

public class Menu {
	private static final Logger log = Logger.getLogger(Menu.class);
	private final List<MenuItem> listOfMenuItems;

	public Menu(List<MenuItem> items) {
		listOfMenuItems = items;
	}

	public void run() {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				System.in));

		while (true) {
			MenuItem item;
			StringBuilder output = new StringBuilder();
			output.append("\n");

			for (int i = 0, k = 1; i < listOfMenuItems.size() - 1; i++) {
				item = listOfMenuItems.get(i);
				output.append("<").append(k).append("> ").append("|")
						.append(item.getCommandName()).append("|\n");
				k++;
			}
			item = listOfMenuItems.get(listOfMenuItems.size() - 1);
			output.append("<0> ").append("|").append(item.getCommandName())
					.append("|");
			log.info(output);
			System.out.println();
			try {
				String commandId = reader.readLine();
				MenuItem selectedMenuItem = null;
				selectedMenuItem = searchCommand(commandId, selectedMenuItem);
				if (selectedMenuItem != null) {
					if (!selectedMenuItem.execute())
						return;
				} else
					throw new NoSuchCommandException();
			}catch (NoSuchCommandException e){
				log.warn(e);
			} catch (IOException e) {
				log.warn("Input problems, try again " + e);
				run();
			}
		}
	}

	private MenuItem searchCommand(String commandId, MenuItem selectedMenuItem) {
		for (MenuItem item : listOfMenuItems) {
			if (commandId.equals(item.getId())) {
				selectedMenuItem = item;
				break;
			}
		}
		return selectedMenuItem;
	}
}
